<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of SitioController
 *
 * @author Nayeli
 */
class UserController extends AppController {

    var $components = array('Email');

    public function beforeFilter() {
        parent::beforeFilter();
    }

    public function add() {
        $this->set('title_for_layout', 'Registarse');
        $this->layout = 'base';
        $this->loadModel("State");
        $this->set('estados', $this->parseForSend($this->State->find('all', array(
                            'fields' => array('id_states', 'name')
        ))));
        $this->loadModel("UserTypes");
        $typeUser = $this->UserTypes->getTypePublic();
        $this->set('tipoUsuario', $this->parseForSend4($typeUser));
       
        $this->setJsVar('urlUsers', $this->_html->url(array('controller' => 'User', 'action' => 'validUser')));

        $imagen = 'banner/masfletes_3.jpg';
        $altima = 'MasFletes_Registrarse';

        if ($this->request->is("post")) {
            $this->User->set($this->data);
            try {
                $datos = $this->request->data;
                $usuario = array();
                $usuario['username'] = $datos['username'];
                $usuario['password'] = md5($datos['password']);
                $usuario['type'] = $datos['type'];
                $usuario['first_name'] = $datos['first_name'];
                $usuario['last_name'] = $datos['last_name'];
                $usuario['address'] = $datos['address'];
                $usuario['state'] = $datos['state'];
                $usuario['city'] = $datos['city'];
                $usuario['zip_code'] = $datos['zip_code'];
                $usuario['razon_social'] = $datos['razon_social'];
                $usuario['phone'] = $datos['phone'];
                $usuario['phoneNextel'] = $datos['phoneNextel'];
                $usuario['rfc'] = $datos['rfc'];
                $this->loadModel('User');

                $var = $this->User->save($usuario);

                $configur = array();
                $configur['user_id'] = $var['User']['id'];
                $configur['email'] = '';
                $configur['send_routes'] = '0';
                $configur['send_shipments'] = '0';
                $configur['send_notifications'] = '0';
                $this->loadModel('ConfigurationsEmail');
                $this->ConfigurationsEmail->save($configur);

                $name = $this->data['first_name'];
                $lastName = $this->data['last_name'];
                $email = $this->data['username'];
                $perfil = $this->data['type'];
                if (empty($this->data['phone'])) {
                    $phone = "No proporciono ningun teléfono";
                } else {
                    $phone = $this->data['phone'];
                }
                if (empty($this->data['phoneNextel'])) {
                    $phone = "No proporciono ningun teléfono";
                } else {
                    $phone = $this->data['phoneNextel'];
                }
                $type = $datos['type'];
                // debe ser mas dinamico
                if ($type == 1) {
                    $typePerfil = "Administrador";
                    $mensasgePD = "<br /><br /><strong>Atentamente MasFletes</strong><br /><br />";
                }
                if ($type == 2) {
                    $typePerfil = "Coordinador";
                    $mensasgePD = "<br /><br />De realizar algun flete con nostros debes presentar el contrato del transportista firmado, "
                            . "es requisito indispensable. <br /><br /><strong>Atentamente MasFletes</strong><br /><br />";
                }
                 if ($type == 3) {
                    $typePerfil = "Enviador";
                    $mensasgePD = "<br /><br /><strong>Atentamente MasFletes</strong><br /><br />";
                }
                if ($type == 4) {
                    $typePerfil = "Transportista";
                    $mensasgePD = "<br /><br />De realizar algun flete con nostros debes presentar el contrato del transportista firmado, "
                            . "es requisito indispensable. <br /><br /><strong>Atentamente MasFletes</strong><br /><br />";
                }

                $menssage = "<strong>Bienvenido a Mas Fletes. </strong><br /><br />Estimado " . $typePerfil . " " . $name . " " . $lastName
                        . ", te damos la m&aacute;s cordial bienvenida a nuestro sistema y a todos los beneficios que este ofrece para "
                        . "satisfacci&oacute;n de tu negocio o empresa, ya que tu eres muy importante para nosotros.<br /><br />Te hemos enviado tambien, adjunto en este correo, una "
                        . "presentaci&oacute;n en formato PDF."
                        . $mensasgePD;

                $this->Email->to = '' . $email . '';
                $this->Email->subject = "Bienvenido a MasFletes.Com ";
                $this->Email->from = "MasFletes.com <administrador@masfletes.com>";
                if ($perfil == 3) {
                    $this->Email->attachments = (array('Bienvenida Enviador.pdf' => ROOT . '/app/webroot/files/Presentaciones/Presentacion Cliente.pdf'));
                }
                if ($perfil == 4) {
                    $this->Email->attachments = (array('Bienvenida Transportista.pdf' => ROOT . '/app/webroot/files/Presentaciones/Presentacion Transportista.pdf', 'Reglamento.pdf' => ROOT . '/app/webroot/files/Presentaciones/Reglamento Transportista.pdf'));
                }
                $this->Email->sendAs = 'both';
                $this->Email->smtpOptions = array('port' => '587', 'timeout' => '30', 'host' => 'mail.masdistribucion.com.mx', 'username' => 'admin@masdistribucion.com.mx', 'password' => 'distribucion2900');
                $this->Email->delivery = "smtp";
                if ($this->Email->send($menssage)) {
                    
                } else {
                    echo $this->Email->smtpError;
                }
                $this->Session->setFlash('Has sido registrado en nuestro sistema, te hemos enviado un correo eletr&oacute;nico a tu cuenta.<br/><strong> Bienvenido a Mas Fletes. </strong>', 'default', array('class' => 'msg_ok'));
                $this->redirect(array('action' => 'add'));
                $this->set('rerror', false);
            } catch (PDOException $e) {
                $this->set('rerror', true);
            }
        }
    }

    public function dameMunicipios() {
        $this->loadModel("City");
        $municipios = $this->parseForSend3($this->Citie->find('all', array(
                    'conditions' => array("id_states" => $this->request->data['id_states']),
                    'fields' => array('id_city', 'name')
        )));
        $this->set(array('municipios' => $municipios, '_serialize' => 'municipios'));
        $this->viewClass = 'Json';
    }

    private function parseForSend($array) {
        $nArray = array();

        foreach ($array as $value) {
            $var = each($value);
            $nArray[$var[1]['id_states']] = $var[1]['name'];
        }

        return $nArray;
    }
     private function parseForSend4($array) {
        $nArray = array();

        foreach ($array as $value) {
            $var = each($value);
            $nArray[$var[1]['id_user_types']] = $var[1]['name'];
        }

        return $nArray;
    }
    private function parseForSend3($array) {
        $nArray = array();

        foreach ($array as $value) {
            $var = each($value);
            $nArray[$var[1]['id_city']] = $var[1]['name'];
        }

        return $nArray;
    }
    public function validUser() {
        if ($this->request->is("post")) {
            $post = $this->request->data;
            $user = $post['username'];
            //la busqueda en la bd
            $this->loadModel('User');
            $usuarios = $this->User->getUserName($user);

            if (count($usuarios) == 0) {
                $usuarios = true;
            } else {
                $usuarios = false;
            }
        }

        $this->set(array('usuarios' => $usuarios, '_serialize' => 'usuarios'));
        $this->viewClass = 'Json';
    }

}

?>
